<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tpshop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: IT宇宙人 2015-08-10 $
 *
 * TPshop为照顾新手，让新手们都能读懂代码，将代码写的比较通俗易懂，不写太过高深代码。
 * 为兼容以前的Thinkphp3.2老用户习惯, 用TP5助手函数实现 M( ) D( ) U( ) S( )等单字母函数
 */ 
 use think\Db;
use phpDocumentor\Reflection\DocBlock\Tag\VarTag;
use think\helper\Time;
use think\Controller;
/**
 * tpshop检验登陆
 * @param
 * @return bool
 */
function is_login(){
    if(isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0){
        return $_SESSION['admin_id'];
    }else{
        return false;
    }
}

/**
 * 检验是否验证手机
 * @param
 * @return bool
 */
function is_mobile_validate(){
    //从cookie中取当前用户数据
    $user = session('user');
    $user_id = $user['user_id'];
    //从数据库取实时数据
    $user = M('users')->where('user_id',$user_id)->find();
    if(!$user['mobile'] || $user['mobile_validated']!=1){
    	return false;
    }
    else{
    	return true;
    }
}

/**
 * 获取用户信息
 * @param $user_id_or_name  用户id 邮箱 手机 第三方id
 * @param int $type  类型 0 user_id查找 1 邮箱查找 2 手机查找 3 第三方唯一标识查找
 * @param string $oauth  第三方来源
 * @return mixed
 */
function get_user_info($user_id_or_name,$type = 0,$oauth=''){
    $map = array();
    if($type == 0)
        $map['user_id'] = $user_id_or_name;
    if($type == 1)
        $map['email'] = $user_id_or_name;
    if($type == 2)
        $map['mobile'] = $user_id_or_name;
    if($type == 3){
        $map['openid'] = $user_id_or_name;
        $map['oauth'] = $oauth;
    }
    if($type == 4){
    	$map['unionid'] = $user_id_or_name;
    	$map['oauth'] = $oauth;
    }
    $user = M('users')->where($map)->find();
    return $user;
}

/**
 * 更新会员等级,折扣，消费总额
 * @param $user_id  用户ID
 * @return boolean
 */
function update_user_level($user_id){
    $level_info = M('user_level')->order('level_id')->select();
    $total_amount = M('order')->where("user_id=:user_id AND pay_status=1 and order_status not in (3,5)")->bind(['user_id'=>$user_id])->sum('order_amount');
    if($level_info){
    	foreach($level_info as $k=>$v){
    		if($total_amount >= $v['amount']){
    			$level = $level_info[$k]['level_id'];
    			$discount = $level_info[$k]['discount']/100;
    		}
    	}
    	$user = session('user');
    	$updata['total_amount'] = $total_amount;//更新累计修复额度
    	//累计额度达到新等级，更新会员折扣
    	if(isset($level) && $level>$user['level']){
    		$updata['level'] = $level;
    		$updata['discount'] = $discount;	
    	}
    	M('users')->where("user_id", $user_id)->save($updata);
    }
}

/**
 *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
 * @param type $goods_id  商品id
 * @param type $width     生成缩略图的宽度
 * @param type $height    生成缩略图的高度
 */
function goods_thum_images($goods_id,$width,$height){

     if(empty($goods_id))
		 return '';
    //判断缩略图是否存在
    $path = "public/upload/goods/thumb/$goods_id/";
    $goods_thumb_name ="goods_thumb_{$goods_id}_{$width}_{$height}";
  
    // 这个商品 已经生成过这个比例的图片就直接返回了
    if(file_exists($path.$goods_thumb_name.'.jpg'))  return '/'.$path.$goods_thumb_name.'.jpg'; 
    if(file_exists($path.$goods_thumb_name.'.jpeg')) return '/'.$path.$goods_thumb_name.'.jpeg'; 
    if(file_exists($path.$goods_thumb_name.'.gif'))  return '/'.$path.$goods_thumb_name.'.gif'; 
    if(file_exists($path.$goods_thumb_name.'.png'))  return '/'.$path.$goods_thumb_name.'.png'; 
        
    $original_img = M('Goods')->where("goods_id", $goods_id)->getField('original_img');
    if(empty($original_img)) return '';
    
    $original_img = '.'.$original_img; // 相对路径
    if(!file_exists($original_img)) return '';

    //$image = new \think\Image();
    $image = \think\Image::open($original_img);
        
    $goods_thumb_name = $goods_thumb_name. '.'.$image->type();
    //生成缩略图
    if(!is_dir($path)) 
        mkdir($path,0777,true);
    
    //参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
    $image->thumb($width, $height,2)->save($path.$goods_thumb_name,NULL,100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
    
    //图片水印处理
    $water = tpCache('water');
    if($water['is_mark']==1){
    	$imgresource = './'.$path.$goods_thumb_name;
    	if($width>$water['mark_width'] && $height>$water['mark_height']){
    		if($water['mark_type'] == 'img'){
    			$image->open($imgresource)->water(".".$water['mark_img'],$water['sel'],$water['mark_degree'])->save($imgresource);
    		}else{
    		    //检查字体文件是否存在
    			if(file_exists('./zhjt.ttf')){
    				$image->open($imgresource)->text($water['mark_txt'],'./zhjt.ttf',20,'#000000',$water['sel'])->save($imgresource);
    			}
    		}
    	}
    }
    return '/'.$path.$goods_thumb_name;
}

/**
 * 商品相册缩略图
 */
function get_sub_images($sub_img,$goods_id,$width,$height){
	//判断缩略图是否存在
	$path = "public/upload/goods/thumb/$goods_id/";
	$goods_thumb_name ="goods_sub_thumb_{$sub_img['img_id']}_{$width}_{$height}";
	//这个缩略图 已经生成过这个比例的图片就直接返回了
	if(file_exists($path.$goods_thumb_name.'.jpg'))  return '/'.$path.$goods_thumb_name.'.jpg';
	if(file_exists($path.$goods_thumb_name.'.jpeg')) return '/'.$path.$goods_thumb_name.'.jpeg';
	if(file_exists($path.$goods_thumb_name.'.gif'))  return '/'.$path.$goods_thumb_name.'.gif';
	if(file_exists($path.$goods_thumb_name.'.png'))  return '/'.$path.$goods_thumb_name.'.png';
	
	$original_img = '.'.$sub_img['image_url']; //相对路径
	if(!file_exists($original_img)) return '';
	
	//$image = new \think\Image();
	//$image->open($original_img);
        $image = \think\Image::open($original_img);
	
	$goods_thumb_name = $goods_thumb_name. '.'.$image->type();
	// 生成缩略图
	if(!is_dir($path))
		mkdir($path,777,true);
	$image->thumb($width, $height,2)->save($path.$goods_thumb_name,NULL,100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
	return '/'.$path.$goods_thumb_name;
}

/**
 * 刷新商品库存, 如果商品有设置规格库存, 则商品总库存 等于 所有规格库存相加
 * @param type $goods_id  商品id
 */
function refresh_stock($goods_id){
    $count = M("SpecGoodsPrice")->where("goods_id", $goods_id)->count();
    if($count == 0) return false; // 没有使用规格方式 没必要更改总库存

    $store_count = M("SpecGoodsPrice")->where("goods_id", $goods_id)->sum('store_count');
    M("Goods")->where("goods_id", $goods_id)->save(array('store_count'=>$store_count)); // 更新商品的总库存
}

/**
 * 根据 order_goods 表扣除商品库存
 * @param type $order_id  订单id
 */
function minus_stock($order_id){
    $orderGoodsArr = M('OrderGoods')->where("order_id", $order_id)->select();
    foreach($orderGoodsArr as $key => $val)
    {
        // 有选择规格的商品
        if(!empty($val['spec_key']))
        {   // 先到规格表里面扣除数量 再重新刷新一个 这件商品的总数量
            M('SpecGoodsPrice')->where("goods_id = :goods_id and `key` = :key")->bind(['goods_id'=>$val['goods_id'],'key'=>$val['spec_key']])->setDec('store_count',$val['goods_num']);
            refresh_stock($val['goods_id']);
        }else{
            M('Goods')->where("goods_id", $val['goods_id'])->setDec('store_count',$val['goods_num']); // 直接扣除商品总数量
        }
        M('Goods')->where("goods_id", $val['goods_id'])->setInc('sales_sum',$val['goods_num']); // 增加商品销售量
        //更新活动商品购买量
        if($val['prom_type']==1 || $val['prom_type']==2){
        	$prom = get_goods_promotion($val['goods_id']);
        	if($prom['is_end']==0){
        		$tb = $val['prom_type']==1 ? 'flash_sale' : 'group_buy';
        		M($tb)->where("id", $val['prom_id'])->setInc('buy_num',$val['goods_num']);
        		M($tb)->where("id", $val['prom_id'])->setInc('order_num');
        	}
        }
    }
}

/**
 * 邮件发送
 * @param $to    接收人
 * @param string $subject   邮件标题
 * @param string $content   邮件内容(html模板渲染后的内容)
 * @throws Exception
 * @throws phpmailerException
 */
function send_email($to,$subject='',$content=''){    
    vendor('phpmailer.PHPMailerAutoload'); ////require_once vendor/phpmailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;
    $config = tpCache('smtp');
	$mail->CharSet  = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = 0;
    //调试输出格式
	//$mail->Debugoutput = 'html';
    //smtp服务器
    $mail->Host = $config['smtp_server'];
    //端口 - likely to be 25, 465 or 587
    $mail->Port = $config['smtp_port'];
	
	if($mail->Port === 465) $mail->SMTPSecure = 'ssl';// 使用安全协议
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //用户名
    $mail->Username = $config['smtp_user'];
    //密码
    $mail->Password = $config['smtp_pwd'];
    //Set who the message is to be sent from
    $mail->setFrom($config['smtp_user']);
    //回复地址
    //$mail->addReplyTo('replyto@example.com', 'First Last');
    //接收邮件方
    if(is_array($to)){
    	foreach ($to as $v){
    		$mail->addAddress($v);
    	}
    }else{
    	$mail->addAddress($to);
    }

    $mail->isHTML(true);// send as HTML
    //标题
    $mail->Subject = $subject;
    //HTML内容转换
    $mail->msgHTML($content);
    //Replace the plain text body with one created manually
    //$mail->AltBody = 'This is a plain-text message body';
    //添加附件
    //$mail->addAttachment('images/phpmailer_mini.png');
    //send the message, check for errors
    return $mail->send();
}

/**
 * 发送短信
 * @param $mobile  手机号码
 * @param $content  内容
 * @return bool

function sendSMS($mobile,$content)
{
    $config = F('sms','',TEMP_PATH);
    $http = $config['sms_url'];			//短信接口
    $uid = $config['sms_user'];			//用户账号
    $pwd = $config['sms_pwd'];			//密码
    $mobileids = $mobile;         		//号码发送状态接收唯一编号
    $data = array
    (
        'uid'=>$uid,					//用户账号
        'pwd'=>md5($pwd.$uid),			//MD5位32密码,密码和用户名拼接字符
        'mobile'=>$mobile,				//号码，以英文逗号隔开
        'content'=>$content,			//内容
        'mobileids'=>$mobileids,
    );
    //即时发送
    $res = httpRequest($http,'POST',$data);//POST方式提交
    $stat = strpos($res,'stat=100');
    if($stat){
        return true;
    }else{
        return false;
    }
}
 */

/**
 * 获取短信配置信息
 * @param unknown $key
 * @return string
 */
function smsConfigValueScene($scene){
    
    $keys = array(
	    'sms_product'=>'sms_product' ,        //产品名称
        1 => 'regis_sms_enable' ,                //1 : 用户注册
	    2=>'forget_pwd_sms_enable',          //2 : 用户找回密码
	    3=>'order_add_sms_enable',            //3. 客户下单
	    4=>'order_pay_sms_enable',             //4.客户支付
	    5=>'order_shipping_sms_enable' ,    //5.商家发货
	    6=> 'bind_mobile_sms_enable'         //6.修改手机号码
	);
	
	$key = $keys[$scene];
	$config = tpCache('sms');  
	$value = $config[$key];
	return $value;
}

/**
 * 检测是否能够发送短信
 * @param unknown $scene
 * @return multitype:number string
 */
function checkEnableSendSms($scene){
    
    $smsEnable = smsConfigValueScene($scene);
    $sendScenes = C('SEND_SCENE');
    $sceneName = $sendScenes[$scene][0];
   
    if(!$smsEnable){
        return array("status"=>-1,"msg"=>"['$sceneName']短信模板已经关闭'");
    }
    
    //判断是否添加"注册模板"
    $size = M('sms_template')->where("send_scene=$scene")->count('tpl_id');
    if(!$size){
        return array("status"=>-1,"msg"=>"请先添加['$sceneName']短信模板");
    }
    
    return array("status"=>1,"msg"=>"可以发送短信");
}

/**
 * 发送短信逻辑
 * @param unknown $scene
 */
function sendSms($scene , $sender, $params){
     
    $smsTemp = M('sms_template')->where("send_scene= :send_scene")->bind(['send_scene'=>$scene])->find();    //用户注册.
    $code = !empty($params['code']) ? $params['code'] : false;
    $consignee = !empty($params['consignee']) ? $params['consignee'] : false;
    $user_name =  !empty($params['user_name']) ? $params['user_name'] : false;
    $order_sn = $params['order_sn'];
    
    $product = smsConfigValueScene('sms_product');
    
   $smsParams = array(
        1 => "{\"code\":\"$code\",\"product\":\"$product\"}",                                                                   //1. 用户注册
        2 => "{\"code\":\"$code\"}",                                                                                                          //2. 用户找回密码
        3 => "{\"consignee\":\"$consignee\",\"phone\":\"$sender\"}",                                                       //3. 客户下单
        4 => "{\"order_sn\":\"$order_sn\"}",                                                                                               //4. 客户支付
        5 => "{\"user_name\":\"$user_name\",\"order_sn\":\"$order_sn\",\"consignee\":\"$consignee\"}",  //5.商家发货
        6 => "{\"user_name\":\"$user_name\",\"code\":\"$code\"}"                                                            //6. 修改手机号码
    );
   
    $smsParam = $smsParams[$scene];
 
	$resp =  realSendSMS($sender, $smsTemp['sms_sign'], $smsParam , $smsTemp['sms_tpl_code']);
	
	if($resp['status'] == 1){
	    $session_id = session_id();
	    // 从数据库中查询是否有验证码
	    $data = M('sms_log')->where(array('mobile' => $sender, 'status'=>0, 'session_id' => $session_id))->order('add_time desc')->find();
	    if(empty($data)){
	        // 没有就插入验证码,供验证用
	        $data = array('mobile' => $sender,  'add_time' => time(),'status'=>1, 'session_id' => $session_id);
	        if($code){
	            $data['code'] = $code;
	        }
	        M('sms_log')->add($data);
	    }else{
	        //修改发送状态为成功
	        M('sms_log')->where(array('id'=>$data['id']))->save(array('status'=>1));
	    }
	}
	return $resp;
}

 

//    /**
//     * 为照顾新手开发者 方便调试, 此方法每一行加以注释说明
//     * 发送短信
//     * @param $mobile  手机号码
//     * @param $smsSign    短信签名 必须
//     * @param smsParam   短信模板 必须
//     * @param $templateCode    短信模板ID，传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。
//     * @return bool    短信发送成功返回true失败返回false
//     */
function realSendSMS($mobile, $smsSign, $smsParam , $templateCode)
{
   
    //时区设置：亚洲/上海
    date_default_timezone_set('Asia/Shanghai');
    //这个是你下面实例化的类
    vendor('Alidayu.TopClient');
    //这个是topClient 里面需要实例化一个类所以我们也要加载 不然会报错
    vendor('Alidayu.ResultSet');
    //这个是成功后返回的信息文件
    vendor('Alidayu.RequestCheckUtil');
    //这个是错误信息返回的一个php文件
    vendor('Alidayu.TopLogger');
    //这个也是你下面示例的类
    vendor('Alidayu.AlibabaAliqinFcSmsNumSendRequest');

   
    $c = new \TopClient;
    $config = tpCache('sms'); 
    //App Key的值 这个在开发者控制台的应用管理点击你添加过的应用就有了
    $c->appkey = $config['sms_appkey'];
    //App Secret的值也是在哪里一起的 你点击查看就有了
    $c->secretKey = $config['sms_secretKey'];
    //这个是用户名记录那个用户操作
    $req = new \AlibabaAliqinFcSmsNumSendRequest;
    //代理人编号 可选
    $req->setExtend("123456");
    //短信类型 此处默认 不用修改
    $req->setSmsType("normal");
    //短信签名 必须
    $req->setSmsFreeSignName($smsSign);
    //短信模板 必须
    $req->setSmsParam($smsParam);
    //短信接收号码 支持单个或多个手机号码，传入号码为11位手机号码，不能加0或+86。群发短信需传入多个号码，以英文逗号分隔，
    $req->setRecNum("$mobile");
    //短信模板ID，传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。
    $req->setSmsTemplateCode($templateCode); // templateCode

    $c->format='json';
    //发送短信
    $resp = $c->execute($req);
    //短信发送成功返回True，失败返回false
    //if (!$resp)
    echo json_encode($resp);
    exit();

    if ($resp && $resp->result)   
    {
        return array('status'=>1 , 'msg'=>$resp->sub_msg);
    }
    else
    {
        return array('status'=>-1 , 'msg'=>$resp->sub_msg.' ,msg :'.$resp->msg.' subcode:'.$resp->sub_code);
    }
}


/*
 * 发送短信(自定义)
 * $mobile : 发送的手机号
 * $type : 发送的类型  
 * 1:注册验证码
 * 2:修改密码验证
 * 3:登陆验证码
 * 4:修改邮箱验证码
 * 5:修改绑定手机验证码
 * 6:物流通知
 * 7:绑定手机
 * $param: 1-5(验证码) 6(订单号)
 */
function sendSMS2($mobile, $type, $param)
{
    date_default_timezone_set('Asia/Shanghai');
    vendor('Alidayu.TopSdk');
//     include "alidayu/TopSdk.php";

    
    $c = new TopClient;
    $c->appkey = "23719110";
    $c->secretKey = "5b08647a555c34f59a2403abb178fc65";
    $req = new AlibabaAliqinFcSmsNumSendRequest;
    $req->setSmsType("normal");
    $req->setSmsFreeSignName("封坛天下");
    switch ($type){
        case 1://注册验证码
            $req->setSmsParam("{\"code\":\"".$param['code']."\"}");
            $req->setSmsTemplateCode("SMS_58120163");
            break;
        case 2://修改密码验证
            $req->setSmsParam("{\"code\":\"".$param['code']."\"}");
            $req->setSmsTemplateCode("SMS_58115179");
            break;
        case 3://登陆验证码
            $req->setSmsParam("{\"code\":\"".$param['code']."\"}");
            $req->setSmsTemplateCode("SMS_57925176");
            break;
        case 4://修改邮箱验证码
            $req->setSmsParam("{\"code\":\"".$param['code']."\"}");
            $req->setSmsTemplateCode("SMS_58105172");
            break;
        case 5://修改绑定手机验证码
            $req->setSmsParam("{\"code\":\"".$param['code']."\"}");
            $req->setSmsTemplateCode("SMS_57935090");
            break;
        case 6://物流通知
            $req->setSmsParam("{\"ordersn\":\"".$param['ordersn']."\"}");
            $req->setSmsTemplateCode("SMS_58530008");
            break;
        case 7://绑定手机验证码
            $req->setSmsParam("{\"code\":\"".$param['code']."\",\"phone\":\"".$param['phone']."\",\"mima\":\"".$param['mima']."\"}");
            $req->setSmsTemplateCode("SMS_61560004");
            break;    
        default:
            return false;//未知短信类型
            break;
    }
    $req->setRecNum($mobile);
    $resp = $c->execute($req);

//     return $resp;
//     //var_dump($resp);
    if ($resp && $resp->result)   
    {
        return array('status'=>1 , 'msg'=>$resp->sub_msg);
    }
    else
    {
        return array('status'=>-1 , 'msg'=>$resp->sub_msg.' ， msg：'.$resp->msg.'， subcode：'.$resp->sub_code);
    }
}


/**
 * 查询快递
 * @param $postcom  快递公司编码
 * @param $getNu  快递单号
 * @return array  物流跟踪信息数组
 */
function queryExpress($postcom , $getNu) {
/*    $url = "http://wap.kuaidi100.com/wap_result.jsp?rand=".time()."&id={$postcom}&fromWeb=null&postid={$getNu}";
    //$resp = httpRequest($url,'GET');
    $resp = file_get_contents($url);
    if (empty($resp)) {
        return array('status'=>0, 'message'=>'物流公司网络异常，请稍后查询');
    }
    preg_match_all('/\\<p\\>&middot;(.*)\\<\\/p\\>/U', $resp, $arr);
    if (!isset($arr[1])) {
        return array( 'status'=>0, 'message'=>'查询失败，参数有误' );
    }else{
        foreach ($arr[1] as $key => $value) {
            $a = array();
            $a = explode('<br /> ', $value);
            $data[$key]['time'] = $a[0];
            $data[$key]['context'] = $a[1];
        }
        return array( 'status'=>1, 'message'=>'1','data'=> array_reverse($data));
    }*/
    $url = "https://m.kuaidi100.com/query?type=".$postcom."&postid=".$getNu."&id=1&valicode=&temp=0.49738534969422676";
    $resp = httpRequest($url,"GET");
    return json_decode($resp,true);
}

/**
 * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getCatGrandson ($cat_id)
{
    $GLOBALS['catGrandson'] = array();
    $GLOBALS['category_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['catGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['category_id_arr'] = M('GoodsCategory')->cache(true,TPSHOP_CACHE_TIME)->getField('id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('GoodsCategory')->where("parent_id", $cat_id)->cache(true,TPSHOP_CACHE_TIME)->getField('id',true);
    foreach($son_id_arr as $k => $v)
    {
        getCatGrandson2($v);
    }
    return $GLOBALS['catGrandson'];
}

/**
 * 获取某个文章分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getArticleCatGrandson ($cat_id)
{
    $GLOBALS['ArticleCatGrandson'] = array();
    $GLOBALS['cat_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['cat_id_arr'] = M('ArticleCat')->getField('cat_id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('ArticleCat')->where("parent_id", $cat_id)->getField('cat_id',true);
    foreach($son_id_arr as $k => $v)
    {
        getArticleCatGrandson2($v);
    }
    return $GLOBALS['ArticleCatGrandson'];
}

/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getCatGrandson2($cat_id)
{
    $GLOBALS['catGrandson'][] = $cat_id;
    foreach($GLOBALS['category_id_arr'] as $k => $v)
    {
        // 找到孙子
        if($v == $cat_id)
        {
            getCatGrandson2($k); // 继续找孙子
        }
    }
}


/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getArticleCatGrandson2($cat_id)
{
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    foreach($GLOBALS['cat_id_arr'] as $k => $v)
    {
        // 找到孙子
        if($v == $cat_id)
        {
            getArticleCatGrandson2($k); // 继续找孙子
        }
    }
}

/**
 * 查看某个用户购物车中商品的数量
 * @param type $user_id
 * @param type $session_id
 * @return type 购买数量
 */
function cart_goods_num($user_id = 0,$session_id = '')
{
    $where = " session_id = :session_id ";
    $bind['session_id'] = $session_id;
    if($user_id){
        $where .= " or user_id = :user_id ";
        $bind['user_id'] = $user_id;
    }
    // 查找购物车数量
    $cart_count =  M('Cart')->where($where)->bind($bind)->sum('goods_num');
    $cart_count = $cart_count ? $cart_count : 0;
    return $cart_count;
}

/**
 * 获取商品库存
 * @param type $goods_id 商品id
 * @param type $key  库存 key
 */
function getGoodNum($goods_id,$key)
{
    if(!empty($key))
        return M("SpecGoodsPrice")->where(['goods_id' => $goods_id, 'key' => $key])->getField('store_count');
    else
        return  M("Goods")->where("goods_id", $goods_id)->getField('store_count');
}
 
/**
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 */
function tpCache($config_key,$data = array()){
    $param = explode('.', $config_key);
    if(empty($data)){
        //如$config_key=shop_info则获取网站信息数组
        //如$config_key=shop_info.logo则获取网站logo字符串
        $config = F($param[0],'',TEMP_PATH);//直接获取缓存文件
        if(empty($config)){
            //缓存文件不存在就读取数据库
            $res = D('config')->where("inc_type",$param[0])->select();
            if($res){
                foreach($res as $k=>$val){
                    $config[$val['name']] = $val['value'];
                }
                F($param[0],$config,TEMP_PATH);
            }
        }
        if(count($param)>1){
            return $config[$param[1]];
        }else{
            return $config;
        }
    }else{
        //更新缓存
        $result =  D('config')->where("inc_type", $param[0])->select();
        if($result){
            foreach($result as $val){
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k=>$v){
                $newArr = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
                if(!isset($temp[$k])){
                    M('config')->add($newArr);//新key数据插入数据库
                }else{
                    if($v!=$temp[$k])
                        M('config')->where("name", $k)->save($newArr);//缓存key存在且值有变更新此项
                }
            }
            //更新后的数据库记录
            $newRes = D('config')->where("inc_type", $param[0])->select();
            foreach ($newRes as $rs){
                $newData[$rs['name']] = $rs['value'];
            }
        }else{
            foreach($data as $k=>$v){
                $newArr[] = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
            }
            M('config')->insertAll($newArr);
            $newData = $data;
        }
        return F($param[0],$newData,TEMP_PATH);
    }
}

/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $desc    变动说明
 * @param   float   distribut_money 分佣金额
 * @return  bool
 */
function accountLog($user_id, $user_money = 0,$pay_points = 0, $desc = '',$distribut_money = 0){
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id'       => $user_id,
        'user_money'    => $user_money,
        'pay_points'    => $pay_points,
        'change_time'   => time(),
        'desc'   => $desc,
    );
    /* 更新用户信息 */
    $sql = "UPDATE __PREFIX__users SET user_money = user_money + $user_money," .
        " pay_points = pay_points + $pay_points, distribut_money = distribut_money + $distribut_money WHERE user_id = $user_id";
    if( DB::execute($sql)){
    	M('account_log')->add($account_log);
        return true;
    }else{
        return false;
    }
}

/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   int     $order_id       订单id
 * @param   float   $user_money     可用余额变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $desc    变动说明
 * @param   float   distribut_money 分佣金额
 * @return  bool
 */
function accountLog2($user_id,$order_id,$user_money = 0,$pay_points = 0, $desc = '',$distribut_money = 0){
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id'       => $user_id,
        'user_money'    => $user_money,
        'pay_points'    => $pay_points,
        'change_time'   => time(),
        'desc'   => $desc,
    );
    /* 插入退款记录 */
    $order_info = M('order')->where("order_id",$order_id)->find();
    $pay_info = M("pay_log")->where("order_sn",$order_info['order_sn'])->find();
    $refund_log = array(
        'user_id' => $user_id,
        'refund_fee' => $user_money,
        'out_refund_no' => "TKWX".getOrdersn(),
        'op_user_id' => '1400627102',
        'addtime' =>time(),
        'status' => 0,
        'return_type' => 0,
    );
    if($pay_info){
        $refund_log['pay_id'] = $pay_info['pay_id'];
        $refund_log['out_refund_no'] = $pay_info['out_trade_no'];
    }
    /* 更新用户信息 */
    $sql = "UPDATE __PREFIX__users SET user_money = user_money + $user_money," .
    " pay_points = pay_points + $pay_points, distribut_money = distribut_money + $distribut_money WHERE user_id = $user_id";
    if( DB::execute($sql)){
        M('account_log')->add($account_log);
        M('refund_log') ->add($refund_log);
        return true;
    }else{
        return false;
    }
}

/**
 * 订单操作日志
 * 参数示例
 * @param type $order_id  订单id
 * @param type $action_note 操作备注
 * @param type $status_desc 操作状态  提交订单, 付款成功, 取消, 等待收货, 完成
 * @param type $user_id  用户id 默认为管理员
 * @return boolean
 */
function logOrder($order_id,$action_note,$status_desc,$user_id = 0,$type = 0)
{
    $status_desc_arr = array('提交订单', '付款成功', '取消', '等待收货', '完成','退货');
    // if(!in_array($status_desc, $status_desc_arr))
    // return false;

    $order = M('order')->where("order_id", $order_id)->find();
    $action_info = array(
        'order_id'        =>$order_id,
        'action_user'     =>$user_id,
        'order_status'    =>$order['order_status'],
        'shipping_status' =>$order['shipping_status'],
        'pay_status'      =>$order['pay_status'],
        'action_note'     => $action_note,
        'status_desc'     =>$status_desc, //''
        'log_time'        =>time(),
        'type'            =>$type 
    );
    return M('order_action')->add($action_info);
}

/*
 * 获取地区列表
 */
function get_region_list(){
    //获取地址列表 缓存读取
    if(!S('region_list')){
        $region_list = M('region')->select();
        $region_list = convert_arr_key($region_list,'id');        
        S('region_list',$region_list);
    }

    return $region_list ? $region_list : S('region_list');
}
/*
 * 获取用户地址列表
 */
function get_user_address_list($user_id){
    $lists = M('user_address')->where(array('user_id'=>$user_id))->select();
    return $lists;
}

/*
 * 获取指定地址信息
 */
function get_user_address_info($user_id,$address_id){
    $data = M('user_address')->where(array('user_id'=>$user_id,'address_id'=>$address_id))->find();
    return $data;
}
/*
 * 获取用户默认收货地址
 */
function get_user_default_address($user_id){
    $data = M('user_address')->where(array('user_id'=>$user_id,'is_default'=>1))->find();
    return $data;
}
/**
 * 获取订单状态的 中文描述名称
 * @param type $order_id  订单id
 * @param type $order     订单数组
 * @return string
 */
function orderStatusDesc($order_id = 0, $order = array())
{
    if(empty($order))
        $order = M('Order')->where("order_id", $order_id)->find();

    // 货到付款
    if($order['pay_code'] == 'cod')
    {
        if(in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0)
            return 'WAITSEND'; //'待发货',
    }
    else // 非货到付款
    {
        if($order['pay_status'] == 0 && $order['order_status'] == 0)
            return 'WAITPAY'; //'待支付',
        if($order['pay_status'] == 1 &&  in_array($order['order_status'],array(0,1)) && $order['shipping_status'] != 1)
            return 'WAITSEND'; //'待发货',
    }
    if(($order['shipping_status'] == 1) && ($order['order_status'] == 1))
        return 'WAITRECEIVE'; //'待收货',
    if($order['order_status'] == 2)
        return 'WAITCCOMMENT'; //'待评价',
    if($order['order_status'] == 3)
        return 'CANCEL'; //'已取消',
    if($order['order_status'] == 4)
        return 'FINISH'; //'已完成',
    if($order['order_status'] == 5)
    	return 'CANCELLED'; //'已作废',
    return 'OTHER';
}

/**
 * 获取订单状态的 显示按钮
 * @param type $order_id  订单id
 * @param type $order     订单数组
 * @return array()
 */
function orderBtn($order_id = 0, $order = array())
{
    if(empty($order))
        $order = M('Order')->where("order_id", $order_id)->find();
    /**
     *  订单用户端显示按钮
    去支付     AND pay_status=0 AND order_status=0 AND pay_code ! ="cod"
    取消按钮  AND pay_status=0 AND shipping_status=0 AND order_status=0
    确认收货  AND shipping_status=1 AND order_status=0
    评价      AND order_status=1
    查看物流  if(!empty(物流单号))
     */
    $btn_arr = array(
        'pay_btn' => 0, // 去支付按钮
        'cancel_btn' => 0, // 取消按钮
        'receive_btn' => 0, // 确认收货
        'comment_btn' => 0, // 评价按钮
        'shipping_btn' => 0, // 查看物流
        'return_btn' => 0, // 退货按钮 (联系客服)
        'contact_btn' => 0,//联系客服(待发货的时候用)
    );


    // 货到付款
    if($order['pay_code'] == 'cod')
    {
        if(($order['order_status']==0 || $order['order_status']==1) && $order['shipping_status'] == 0) // 待发货
        {
            $btn_arr['cancel_btn'] = 1; // 取消按钮 (联系客服)
        }
        if($order['shipping_status'] == 1 && $order['order_status'] == 1) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }       
    }
    // 非货到付款
    else
    {
        if($order['pay_status'] == 0 && $order['order_status'] == 0) // 待支付
        {
            $btn_arr['pay_btn'] = 1; // 去支付按钮
            $btn_arr['cancel_btn'] = 1; // 取消按钮
        }
        if($order['pay_status'] == 1 && in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0) // 待发货
        {
        	$btn_arr['contact_btn'] = 1; //联系客服
        	//$btn_arr['cancel_btn'] = 1; // 取消按钮
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
        if($order['pay_status'] == 1 && $order['order_status'] == 1  && $order['shipping_status'] == 1) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
    }
    if($order['order_status'] == 2)
    {
        $btn_arr['comment_btn'] = 1;  // 评价按钮
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
    }
    if($order['shipping_status'] != 0)
    {
        $btn_arr['shipping_btn'] = 1; // 查看物流
    }
    if($order['shipping_status'] == 2 && $order['order_status'] == 1) // 部分发货
    {            
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
    }
    
    return $btn_arr;
}

/**
 * 给订单数组添加属性  包括按钮显示属性 和 订单状态显示属性
 * @param type $order
 */
function set_btn_order_status($order)
{
    $order_status_arr = C('ORDER_STATUS_DESC');
    $order['order_status_code'] = $order_status_code = orderStatusDesc(0, $order); // 订单状态显示给用户看的
    $order['order_status_desc'] = $order_status_arr[$order_status_code];
    $orderBtnArr = orderBtn(0, $order);
    return array_merge($order,$orderBtnArr); // 订单该显示的按钮
}


/**
 * 支付完成修改订单
 * @param $order_sn 订单号
 * @param array $ext 额外参数
 * @return bool|void
 */
function update_pay_status($order_sn,$ext=array())
{
	if(stripos($order_sn,'recharge') !== false){
		//用户在线充值
		$count = M('recharge')->where("order_sn = :order_sn and pay_status = 0")->bind(['order_sn'=>$order_sn])->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
		if($count == 0) return false;
		$order = M('recharge')->where("order_sn", $order_sn)->find();
		M('recharge')->where("order_sn",$order_sn)->save(array('pay_status'=>1,'pay_time'=>time()));
		accountLog($order['user_id'],$order['account'],0,'会员在线充值');
	}else{
		// 如果这笔订单已经处理过了
		$count = M('order')->where("order_sn = :order_sn and pay_status = 0")->bind(['order_sn'=>$order_sn])->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
		$indiana_count = M('user_indiana')->where("order_sn = :order_sn and pay_status = 0")->bind(['order_sn'=>$order_sn])->count();//一元夺宝订单是否处理
		if($count == 0 && $indiana_count == 0) return false;
		
		// 找出对应的订单
		$order = M('order')->where("order_sn",$order_sn)->find();
		
		//file_put_contents("./public/log/notify_data.txt","\r\n执行到更新订单状态了",FILE_APPEND);
		if(empty($order)){//普通订单没数据，则继续找一元夺宝、提酒等其他订单
			$order = M('user_indiana')->where("order_sn",$order_sn)->find();
			$sql = M('user_indiana')->getLastSql();
			//file_put_contents("./public/log/notify_data.txt","\r\n查询语句：".$sql,FILE_APPEND);
			if($order){
				indiana_pay_ok($order['id']);//一元夺宝订单状态更新
				exit;
			}
		}
		else{
			
		// 修改支付状态  已支付
		M('order')->where("order_sn", $order_sn)->save(array('pay_status'=>1,'pay_time'=>time()));
		// 减少对应商品的库存
		minus_stock($order['order_id']);
		// 给他升级, 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额
		update_user_level($order['user_id']);
		// 记录订单操作日志
        if(is_array($ext) && array_key_exists('admin_id',$ext)){
            logOrder($order['order_id'],$ext['note'],'付款成功',$ext['admin_id'],1);
        }else{
            logOrder($order['order_id'],'订单付款成功','付款成功',$order['user_id']);
        }
		//分销设置
//		M('rebate_log')->where("order_id" ,$order['order_id'])->save(array('status'=>1));
//		// 成为分销商条件
//		$distribut_condition = tpCache('distribut.condition');
//		if($distribut_condition == 1)  // 购买商品付款才可以成为分销商
//			M('users')->where("user_id", $order['user_id'])->save(array('is_distribut'=>1));
		
		//用户支付, 发送短信给商家
//		$res = checkEnableSendSms("4");
//		if(!$res || $res['status'] !=1) return ;
//			
//		$sender = tpCache("shop_info.mobile");
//		if(empty($sender))return;
//		$params = array('order_sn'=>$order_sn);
//		sendSms("4", $sender, $params);

        //支付成功，推送微信消息
        // 如果有微信公众号 则推送一条消息到微信
        $user = M('users')->where("user_id", $order['user_id'])->find();
        if($user['oauth']== 'weixin')
        {
            $wx_user = M('wx_user')->find();
            $jssdk = new \app\mobile\logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
            $wx_content = "您的订单:{$order['order_sn']} 已支付成功";
            $jssdk->push_msg($user['openid'],$wx_content);
        }
        }
	}

}

    /**
     * 订单确认收货
     * @param $id   订单id
     */
    function confirm_order($id,$user_id = 0){
        
        $where = "order_id = :id";
        $bind['id'] = $id;
        $user_id && $where .= " and user_id = $user_id ";
        
        $order = M('order')->where($where)->bind($bind)->find();
        if($order['order_status'] != 1)
            return array('status'=>-1,'msg'=>'该订单不能收货确认');
        
        $data['order_status'] = 2; // 已收货        
        $data['pay_status'] = 1; // 已付款        
        $data['confirm_time'] = time(); // 收货确认时间
        if($order['pay_code'] == 'cod'){
        	$data['pay_time'] = time();
        }

        $row = M('order')->where(array('order_id'=>$id))->save($data);
        if(!$row)        
            return array('status'=>-3,'msg'=>'操作失败');
        
        order_give($order);// 调用送礼物方法, 给下单这个人赠送相应的礼物
        
        //分销设置
        M('rebate_log')->where("order_id", $id)->save(array('status'=>2,'confirm'=>time()));
           
        //分销利润分成  上级6% 上上级5% 
        //上级7%
        if($order['is_distribut'] == 0){
            
            $first_rate = tpCache("distribut.first_rate")/100;
            $second_rate = tpCache("distribut.second_rate")/100;
            $userinfo = M('users')->where("user_id",$user_id)->find();
            if($userinfo['first_leader']){
                //获取订单分销收益价格
                $order_goods = M('order_goods')
                                ->alias("og")
                                ->join("goods g","og.goods_id = g.goods_id")
                                ->where("og.order_id = $id  and g.is_distribut = 0")
                                ->select();
                foreach ($order_goods as $key=>$value){
                    $no_calculate += ($value['shop_price'] - $value['deduction_amount'])*$value['goods_num'];//不参与分销的商品总价
                }
                $distribut_sum_price = $order['goods_price'] - $no_calculate;
                
                if($distribut_sum_price > 0){//如果分销金额大于0
                    $parentinfo = M('users')->where("user_id",$userinfo['first_leader'])->find();
                    $usermoney['user_money'] = $parentinfo['user_money'] + $distribut_sum_price*$first_rate;
                    $result = M('users') ->where('user_id',$parentinfo['user_id'])->save($usermoney);//上级分成6%
                    if($result){
                        log_error("分销收益添加失败:userid=".$parentinfo['userid']."   orderid=".$order['order_id']."  收益金额:".$distribut_sum_price*$first_rate);
                    }
                    income_action(2,7,"获得下线收益1",$distribut_sum_price*$first_rate,$parentinfo['user_id']);//记录分销收益
                    SendMessage(0,1,"你有一笔分销收益已存入您的余额,收益金额:".$distribut_sum_price*$first_rate,array($parentinfo['user_id']),"分销收益通知","/Mobile/User/money_detail");//发送站内信
                    if($parentinfo['first_leader']){
                        $grandInfo = M('users')->where("user_id",$parentinfo['first_leader'])->find();
                        $usermoney['user_money'] = $grandInfo['user_money'] + $distribut_sum_price*$second_rate;
                        $result1 = M('users') ->where('user_id',$grandInfo['user_id'])->save($usermoney);//上级分成5%
                        if($result1){
                            log_error("分销收益添加失败:userid=".$grandInfo['userid']."   orderid=".$order['order_id']."  收益金额:".$distribut_sum_price*$second_rate);
                        }
                        income_action(2,7,"获得下线收益2",$distribut_sum_price*$second_rate,$grandInfo['user_id']);//记录分销收益
                        SendMessage(0,1,"你有一笔分销收益已存入您的余额,收益金额:".$distribut_sum_price*$second_rate,array($grandInfo['user_id']),"分销收益通知","/Mobile/User/money_detail");//发送站内信
                    }
                }
            }

            M('order')->where(array('order_id'=>$id))->save(array('is_distribut'=>1)); //标记订单已分成
            
        }
        return array('status'=>1,'msg'=>'操作成功');
    }

/**
 * 给订单送券送积分 送东西
 */
function order_give($order)
{
	$order_goods = M('order_goods')->where("order_id",$order['order_id'])->cache(true)->select();
	//查找购买商品送优惠券活动
	foreach ($order_goods as $val)
    {
		if($val['prom_type'] == 3)
        {
			$prom = M('prom_goods')->where('type=3 and id=:id')->bind(['id'=>$val['prom_id']])->find();
			if($prom){
				$coupon = M('coupon')->where("id", $prom['expression'])->find();//查找优惠券模板
				if($coupon && $coupon['createnum']>0){					                                        
                    $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                    if($remain > 0)                                            
                    {
                        $data = array('cid'=>$coupon['id'],'type'=>$coupon['type'],'uid'=>$order['user_id'],'send_time'=>time());
                        M('coupon_list')->add($data);       
                        M('Coupon')->where("id", $coupon['id'])->setInc('send_num'); // 优惠券领取数量加一
                    }
				}
		 	}
		 }
	}
	
	//查找订单满额送优惠券活动
	$pay_time = $order['pay_time'];
	$prom = M('prom_order')
        ->where("type>1 and end_time>:pay_time1 and start_time<:pay_time2 and money<=:money")
        ->bind(['pay_time1'=>$pay_time,'pay_time2'=>$pay_time,'money'=>$order['order_amount']])
        ->order('money desc')
        ->find();
	if($prom){
		if($prom['type']==3){
			$coupon = M('coupon')->where("id",$prom['expression'])->find();//查找优惠券模板
			if($coupon){
				if($coupon['createnum']>0){
					$remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                    if($remain > 0)
                    {
                       $data = array('cid'=>$coupon['id'],'type'=>$coupon['type'],'uid'=>$order['user_id'],'send_time'=>time());
                       M('coupon_list')->add($data);           
                       M('Coupon')->where("id",$coupon['id'])->setInc('send_num'); // 优惠券领取数量加一
                    }				
				}
			}
		}else if($prom['type']==2){
			//income_action(0,1,'订单活动赠送',$prom['expression'],$order['user_id']);//收货完成，赠送银酒币，记录收益流水日志
			accountLog($order['user_id'], 0 , $prom['expression'] ,"订单活动赠送银酒币");
		}
	}
    $points = M('order_goods')->where("order_id", $order['order_id'])->sum("give_integral * goods_num");
    //income_action(0,1,'下单赠送',$points,$order['user_id']);//收货完成，赠送银酒币，记录收益流水日志
    accountLog($order['user_id'], 0,$points,"下单赠送银酒币");
}


/**
 * 查看商品是否有活动
 * @param goods_id 商品ID
 */

function get_goods_promotion($goods_id,$user_id=0){
	$now = time();
	$goods = M('goods')->where("goods_id", $goods_id)->find();
    $where = [
        'end_time' => ['gt', $now],
        'start_time' => ['lt', $now],
        'id' => $goods['prom_id'],
    ];
	
	$prom['price'] = $goods['shop_price'];
	$prom['prom_type'] = $goods['prom_type'];
	$prom['prom_id'] = $goods['prom_id'];
	$prom['is_end'] = 0;
	
	if($goods['prom_type'] == 1){//抢购
		$prominfo = M('flash_sale')->where($where)->find();
		if(!empty($prominfo)){
			if($prominfo['goods_num'] == $prominfo['buy_num']){
				$prom['is_end'] = 2;//已售馨
			}else{
				//核查用户购买数量
				$where = "user_id = :user_id and order_status!=3 and  add_time>".$prominfo['start_time']." and add_time<".$prominfo['end_time'];
				$order_id_arr = M('order')->where($where)->bind(['user_id'=>$user_id])->getField('order_id',true);
				if($order_id_arr){
					$goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (".implode(',', $order_id_arr).")")->sum('goods_num');
					if($goods_num < $prominfo['buy_limit']){
						$prom['price'] = $prominfo['price'];
					}
				}else{
					$prom['price'] = $prominfo['price'];
				}
			} 				
		}
	}
	
	if($goods['prom_type']==2){//团购
		$prominfo = M('group_buy')->where($where)->find();
		if(!empty($prominfo)){			
			if($prominfo['goods_num'] == $prominfo['buy_num']){
				$prom['is_end'] = 2;//已售馨
			}else{
				$prom['price'] = $prominfo['price'];
			}				
		}
	}
	if($goods['prom_type'] == 3){//优惠促销
		$parse_type = array('0'=>'直接打折','1'=>'减价优惠','2'=>'固定金额出售','3'=>'买就赠优惠券','4'=>'买M件送N件');
		$prominfo = M('prom_goods')->where($where)->find();
		if(!empty($prominfo)){
			if($prominfo['type'] == 0){
				$prom['price'] = $goods['shop_price']*$prominfo['expression']/100;//打折优惠
			}elseif($prominfo['type'] == 1){
				$prom['price'] = $goods['shop_price']-$prominfo['expression'];//减价优惠
			}elseif($prominfo['type']==2){
				$prom['price'] = $prominfo['expression'];//固定金额优惠
			}
		}
	}
	
	if(!empty($prominfo)){
		$prom['start_time'] = $prominfo['start_time'];
		$prom['end_time'] = $prominfo['end_time'];
	}else{
		$prom['prom_type'] = $prom['prom_id'] = 0 ;//活动已过期
		$prom['is_end'] = 1;//已结束
	}
	
	if($prom['prom_id'] == 0){
		M('goods')->where("goods_id", $goods_id)->save($prom);
	}
	return $prom;
}

/**
 * 查看订单是否满足条件参加活动
 * @param order_amount 订单应付金额
 */
function get_order_promotion($order_amount){
	$parse_type = array('0'=>'满额打折','1'=>'满额优惠金额','2'=>'满额送倍数积分','3'=>'满额送优惠券','4'=>'满额免运费');
	$now = time();
	$prom = M('prom_order')->where("type<2 and end_time>$now and start_time<$now and money<=$order_amount")->order('money desc')->find();
	$res = array('order_amount'=>$order_amount,'order_prom_id'=>0,'order_prom_amount'=>0);
	if($prom){
		if($prom['type'] == 0){
			$res['order_amount']  = round($order_amount*$prom['expression']/100,2);//满额打折
			$res['order_prom_amount'] = $order_amount - $res['order_amount'] ;
			$res['order_prom_id'] = $prom['id'];
		}elseif($prom['type'] == 1){
			$res['order_amount'] = $order_amount- $prom['expression'];//满额优惠金额
			$res['order_prom_amount'] = $prom['expression'];
			$res['order_prom_id'] = $prom['id'];
		}
	}
	return $res;		
}

/**
 * 计算订单金额
 * @param type $user_id  用户id
 * @param type $order_goods  购买的商品
 * @param type $shipping  物流code
 * @param type $shipping_price 物流费用, 如果传递了物流费用 就不在计算物流费
 * @param type $province  省份
 * @param type $city 城市
 * @param type $district 县
 * @param type $pay_points 积分
 * @param type $user_money 余额
 * @param type $coupon_id  优惠券
 * @param type $couponCode  优惠码
 */

function calculate_price($user_id = 0, $order_goods, $shipping_code = '', $shipping_price = 0, $province = 0, $city = 0, $district = 0, $pay_points = 0, $user_money = 0, $coupon_id = 0, $couponCode = '')
{
    $cartLogic = new app\home\logic\CartLogic();
    $user = M('users')->where("user_id", $user_id)->find();// 找出这个用户

    if (empty($order_goods)){
        return array('status' => -9, 'msg' => '商品列表不能为空', 'result' => '');
    }

    $goods_id_arr = get_arr_column($order_goods, 'goods_id');
    $goods_arr = M('goods')->where("goods_id in(" . implode(',', $goods_id_arr) . ")")->cache(true,TPSHOP_CACHE_TIME)->getField('goods_id,weight,market_price,is_free_shipping'); // 商品id 和重量对应的键值对
    
    foreach ($order_goods as $key => $val) {
        // 如果传递过来的商品列表没有定义会员价
        if (!array_key_exists('member_goods_price', $val)) {
            $user['discount'] = $user['discount'] ? $user['discount'] : 1; // 会员折扣 不能为 0
            $order_goods[$key]['member_goods_price'] = $val['member_goods_price'] = $val['goods_price'] * $user['discount'];
        }
        //如果商品不是包邮的
        if ($goods_arr[$val['goods_id']]['is_free_shipping'] == 0)
            $goods_weight += $goods_arr[$val['goods_id']]['weight'] * $val['goods_num']; //累积商品重量 每种商品的重量 * 数量

        $order_goods[$key]['goods_fee'] = $val['goods_num'] * ($val['member_goods_price']-$val['deduction_amount']);    // 小计
        $order_goods[$key]['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']); // 最多可购买的库存数量
        if ($order_goods[$key]['store_count'] <= 0)
            return array('status' => -10, 'msg' => $order_goods[$key]['goods_name'] . "库存不足,请重新下单", 'result' => '');

        $goods_price += $order_goods[$key]['goods_fee']; // 商品总价
        $cut_fee += $val['goods_num'] * $val['market_price'] - $val['goods_num'] * $val['member_goods_price']; // 共节约
        $anum += $val['goods_num']; // 购买数量
    }
    // 优惠券处理操作
    $coupon_price = 0;
    if ($coupon_id && $user_id) {
        $coupon_price = $cartLogic->getCouponMoney($user_id, $coupon_id, 1); // 下拉框方式选择优惠券
    }
    if ($couponCode && $user_id) {
        $coupon_result = $cartLogic->getCouponMoneyByCode($couponCode, $goods_price); // 根据 优惠券 号码获取的优惠券
        if ($coupon_result['status'] < 0)
            return $coupon_result;
        $coupon_price = $coupon_result['result'];
    }

    // 处理物流
    if ($shipping_price == 0) {	
        $freight_free = tpCache('shopping.freight_free'); // 全场满多少免运费
        if ($freight_free > 0 && $goods_price >= $freight_free) {
            $shipping_price = 0;
        } else {
            $shipping_price = $cartLogic->cart_freight2($shipping_code, $province, $city, $district, $goods_weight);
        }
    }
    
    if ($pay_points && ($pay_points > $user['pay_points']))
        return array('status' => -5, 'msg' => "你的账户可用积分为:" . $user['pay_points'], 'result' => ''); // 返回结果状态
    if ($user_money && ($user_money > $user['user_money']))
        return array('status' => -6, 'msg' => "你的账户可用余额为:" . $user['user_money'], 'result' => ''); // 返回结果状态
    $order_amount = $goods_price + $shipping_price - $coupon_price; // 应付金额 = 商品价格 + 物流费 - 优惠券
 
    $pay_points = ($pay_points / tpCache('shopping.point_rate')); // 积分支付 100 积分等于 1块钱
    $pay_points = ($pay_points > $order_amount) ? $order_amount : $pay_points; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
    $order_amount = $order_amount - $pay_points; //  积分抵消应付金额

    $user_money = ($user_money > $order_amount) ? $order_amount : $user_money;  // 余额支付原理等同于积分
    $order_amount = $order_amount - $user_money; //  余额支付抵应付金额

    $total_amount = $goods_price + $shipping_price;
    //订单总价  应付金额  物流费  商品总价 节约金额 共多少件商品 积分  余额  优惠券
    $result = array(
        'total_amount' => $total_amount, // 商品总价
        'order_amount' => $order_amount, // 应付金额
        'shipping_price' => $shipping_price, // 物流费
        'goods_price' => $goods_price, // 商品总价
        'cut_fee' => $cut_fee, // 共节约多少钱
        'anum' => $anum, // 商品总共数量
        'integral_money' => $pay_points,  // 积分抵消金额
        'user_money' => $user_money, // 使用余额
        'coupon_price' => $coupon_price,// 优惠券抵消金额
        'order_goods' => $order_goods, // 商品列表 多加几个字段原样返回
    );
    
    return array('status' => 1, 'msg' => "计算价钱成功", 'result' => $result); // 返回结果状态
}

/**
 * 获取商品一二三级分类
 * @return type
 */
function get_goods_category_tree(){
	$result = array();
	$cat_list = M('goods_category')->where("is_show = 1")->order('sort_order')->cache(true)->select();//所有分类
	
	foreach ($cat_list as $val){
		if($val['level'] == 2){
			$arr[$val['parent_id']][] = $val;
		}
		if($val['level'] == 3){
			$crr[$val['parent_id']][] = $val;
		}
		if($val['level'] == 1){
			$tree[] = $val;
		}
	}
    if(!empty($arr)){
        foreach ($arr as $k=>$v){
			foreach ($v as $kk=>$vv){
				$arr[$k][$kk]['sub_menu'] = empty($crr[$vv['id']]) ? array() : $crr[$vv['id']];
			}
		}	
    }
	
	if(!empty($tree)){
		foreach ($tree as $val){
			$val['tmenu'] = empty($arr[$val['id']]) ? array() : $arr[$val['id']];
			$result[$val['id']] = $val;
		}
	}
	return $result;
}

/**
 * 写入静态页面缓存
 */
function write_html_cache($html){
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module().'_'.$request->controller().'_'.$request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('write_html_cache写入缓存<br/>');
    foreach($html_cache_arr as $key=>$val)
    {
        $val['mca'] = strtolower($val['mca']);
        if($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;
        
        if(!is_dir(RUNTIME_PATH.'html'))
                mkdir(RUNTIME_PATH.'html');
        $filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
        // 组合参数  
        if(isset($val['p']))
        {                    
            foreach($val['p'] as $k=>$v)        
                $filename.='_'.$_GET[$v];
        } 
        $filename.= '.html';        
        file_put_contents($filename, $html);
    }    
}

/**
 * 读取静态页面缓存
 */
function read_html_cache(){    
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module().'_'.$request->controller().'_'.$request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('read_html_cache读取缓存<br/>');
    foreach($html_cache_arr as $key=>$val)
    {
        $val['mca'] = strtolower($val['mca']);
        if($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;
          
        $filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
        // 组合参数        
        if(isset($val['p']))
        {                    
            foreach($val['p'] as $k=>$v)        
                $filename.='_'.$_GET[$v];
        } 
        $filename.= '.html';
        if(file_exists($filename))
        {
            echo file_get_contents($filename);           
            exit();           
        }
    }    
}



/***
 * 查询分销收益
 */
function get_distribut_income($user_id){
    
    //查询自己的消费额
    $my_orders = M("order")->where('user_id',$user_id)->select();
    foreach($my_orders as $key=>$val){
		$mycost += ($val['order_amount']-$val['shipping_price']);
	}
    
    //查询一级下线收益
	$my_first_users = M('users')->where('first_leader',$user_id)->select();
	foreach($my_first_users as $key=>$val){
		$f_uid[] = $val['user_id'];
	}
	if(!empty($f_uid)){
    	$where['user_id']  = ['in',$f_uid];
    	
    	//总收益
    	$f_dis_orders = M("order")->where($where)->select();
    	foreach($f_dis_orders as $key=>$val){
    		$total1 += ($val['order_amount']-$val['shipping_price'])*0.06;
    	}
    	//今日收益
    	$f_today_orders = M("order")->where($where)->whereTime('confirm_time', 'today')->select();
    	foreach($f_today_orders as $key=>$val){
    		$today_total1 += ($val['order_amount']-$val['shipping_price'])*0.06;
    	}
	}
	
	//查询二级下线收益
	$my_second_users = M('users')->where('second_leader',$user_id)->select();
	foreach($my_second_users as $key=>$val){
		$s_uid[] = $val['user_id'];
	}
	if(!empty($s_uid)){
		$where['user_id']  = ['in',$s_uid];
		
		//总收益
    	$s_dis_orders = M("order")->where($where)->select();
    	foreach($s_dis_orders as $key=>$val){
    		$total2 += $val['order_amount']-$val['shipping_price']*0.05;
    	}
    	
    	//今日收益
    	$s_today_orders = M("order")->where($where)->whereTime('confirm_time', 'today')->select();
    	foreach($s_today_orders as $key=>$val){
    		$today_total2 += ($val['order_amount']-$val['shipping_price'])*0.05;
    	}
	}
	$mycost = empty($mycost)?0:$mycost;
	$total = sprintf("%.2f",$total1+$total2);
	$today_total = sprintf("%.2f",$today_total1+$today_total2);
	
	return array('mycost'=>$mycost,'total'=>$total,'today_total'=>$today_total);
}


/***
 * 对提酒订单进行操作
 */
function cellar_order_action($action,$recod_id,$msg){
	
    //状态说明
	//  pay 支付
	//  pay_cancel 取消支付
	//  delivery 发货
	//  stocking  备货
	//  delivery_cancel 取消发/备货
	//  receive 确认收货
	//  invalid 订单作废
	//  remove 移除
    
    $model = M('cellar_record');
    $user = session('user');
  
	$cellar_record = $model->where('id',$recod_id)->find();
	$order_info = json_decode($cellar_record['order_info'],true);
	if(!empty($cellar_record['order_action'])){
		$order_action = json_decode($cellar_record['order_action'],true);
	}
	else{
	    $order_action = array();	
	}
    
    if($action == 'pay'){    //支付		
    	$order_info['pay_status'] = 1; //设为已付款
    	$order_info['pay_time'] = time();
    	$push_action['status_desc'] = "付款";
    }
    if($action == 'pay_cancel'){  //取消支付
    	$order_info['pay_status'] = 0; //设为未付款
    	$order_info['pay_time'] = 0;
    	$order_info['order_status'] = 0;
    	$push_action['status_desc'] = "取消付款";
    }
	if($action == 'delivery'){ //发货
		$order_info['order_status'] = 1; //设为已发货
    	$push_action['status_desc'] = "发货";
	}
	if($action == 'stocking'){ //备货
		$order_info['order_status'] = 3; //设为已备货状态
    	$push_action['status_desc'] = "进行备货";
	}
	if($action == 'delivery_cancel'){ //取消发货
		$order_info['order_status'] = 0; //设为未发货状态
		$order_info['invoice_no'] = '';//清空物流单号
    	$push_action['status_desc'] = "取消发/备货";
	}
	if($action == 'invalid'){ //取消订单
		$order_info['order_status'] = 5; //设为作废状态
    	$push_action['status_desc'] = "订单作废";
	}
	if($action == 'receive'){ //确认收货
		$order_info['order_status'] = 2; //确认收货
    	$push_action['status_desc'] = "确认收货，订单完成";
	}
	if($action == 'remove'){ //移除订单
		$a = $model->where(array('id'=>$recod_id))->delete();
		return $a;
	}

	$push_action['pay_status'] = $order_info['pay_status'];
	$push_action['order_status'] = $order_info['order_status'];
	$push_action['action_user'] = $user['user_id'];
	$push_action['action_note'] = $msg;
	$push_action['log_time'] = time();
   
    	
    $cellar_record['order_info'] = json_encode($order_info);
	array_push($order_action,$push_action);
	$cellar_record['order_action'] = json_encode($order_action);
	$msg = $model->where('id',$recod_id)->save($cellar_record);
	return $msg;
	

}


/***
 * 用户收益日志记录
 * $source 收益获得途径  [0:利率，1:购买商品，2:签到，3:活动任务，4:论坛奖励，5:酒币兑换，6:充值，7:分销收益，8:退款]
 * $source_name 收益获得具体途径描述
 * $amount 获得数量
 * $type 收益类型 0:银酒币  1：金酒币   2：余额
 */
function income_action($type,$source,$source_name,$amount,$user_id=0){
	if($user_id == 0){
	$user = session('user');
	$data['uid'] = $user['user_id'];
	}
	else{
	   $data['uid'] = $user_id;	
	}
	$data['amount'] = $amount;
	$data['type'] = $type;
	$data['source_name'] = $source_name;
	$data['source'] = $source;
	$data['add_time'] = time();
    $r = M('user_income')->add($data);//写入记录表
    
    return $r;
}



/***
 * 一元夺宝订单操作日志
 */
function indiana_order_action($action,$indiana_id,$msg){
	
    //状态说明
	//  pay 支付
	//  pay_cancel 取消支付
	//  delivery 发货
	//  stocking  备货
	//  delivery_cancel 取消发/备货
	//  receive 确认收货
	//  invalid 订单作废
	//  remove 移除
    
    $model = M('user_indiana');
    $user = session('user');
  
	$order_info = $model->where('id',$indiana_id)->find();
	if(!empty($order_info['order_action'])){
		$order_action = json_decode($order_info['order_action'],true);
	}
	else{
		$order_action = array();
	}
    
    if($action == 'insert'){    		
    	$push_action['status_desc'] = "提交订单参与夺宝";
    }
    
    if($action == 'pay'){    //支付		
    	$order_info['pay_status'] = 1; //设为已付款
    	$order_info['pay_time'] = time();
    	if(empty($order_info['indiana_number'])){
    		$order_info['indiana_number'] = indiana_rancode($indiana_id);//如果是系统管理强制付款，则执行这步
    	}
    	$push_action['status_desc'] = "付款";
    }
    if($action == 'pay_cancel'){  //取消支付
    	$order_info['pay_status'] = 0; //设为未付款
    	$order_info['pay_time'] = 0;
    	$order_info['order_status'] = 0;
  	    indiana_recovery_code($indiana_id);
  	    $order_info['indiana_number'] = '';//增加库存后，清空订单中的编码	

    	$push_action['status_desc'] = "取消付款";
    }
	if($action == 'delivery'){ //发货
		$order_info['order_status'] = 1; //设为已发货
    	$push_action['status_desc'] = "发货";
	}
	if($action == 'delivery_cancel'){ //取消发货
		$order_info['order_status'] = 0; //设为未发货状态
		$order_info['shipping_info'] = '';//清空物流数据;
    	$push_action['status_desc'] = "取消发货";
	}
	if($action == 'invalid'){ //取消订单
		$order_info['order_status'] = 5; //设为作废状态
    	$push_action['status_desc'] = "订单作废";
	}
	if($action == 'receive'){ //确认收货
		$order_info['order_status'] = 2; //确认收货
    	$push_action['status_desc'] = "确认收货，订单完成";
	}
	if($action == 'remove'){ //移除订单
		$a = M('user_indiana')->where(array('id'=>$recod_id))->delete();
		return $a;
	}

    $push_action['action_user'] = $user['user_id'];
    $push_action['order_status'] = $order_info['order_status'];
    $push_action['pay_status'] = $order_info['pay_status'];
	$push_action['action_note'] = $msg;
	$push_action['log_time'] = time();
    	
	array_push($order_action,$push_action);

	$order_info['order_action'] = json_encode($order_action);
	
	$msg = M('user_indiana')->where('id',$indiana_id)->save($order_info);
	return $msg;
	

}


/*
 * 随机生成夺宝编码
 */
function indiana_rancode($id){
	    $code = '';
	    $order = M('user_indiana')->where('id',$id)->find();
	    $indiana = M('indiana_sale')->where("id",$order['indiana_id'])->find();
	    if($indiana['stock_num'] < $order['num']){
	    	M('user_indiana')->where('id',$id)->save(array('order_status'=>7));//库存不足，订单过期
	    	$this->error('用户未及时付款，目前库存不足，订单已作废',U('Admin/order/indiana_order_info/',array('id'=>$id)));
	    }
	    else{
	        $stock_num = $indiana['stock_num'] - $order['num'];//减编号库存
		    M('indiana_sale')->where("id",$order['indiana_id'])->save(array('stock_num'=>$stock_num));	
    	}
 
    		//随机获取获奖号码
		if($indiana['indiana_number']){
		    $allnum = $ter = json_decode($indiana['indiana_number'],true);
		    $existNum = M('user_indiana')->where("indiana_id",$order['indiana_id'])->field("indiana_number")->select();
		    $eis = array();  		   
	   	    foreach($existNum as $key=>$val){
	   	    	if(!empty($val['indiana_number'])){
	   	    	    $t = json_decode($val['indiana_number'],true);
	   	  	        $eis = array_merge($eis,$t);	
	   	    	}
	   	    }
	   	    if(!empty($eis)){
	   	    	foreach($allnum as $key=>$val){
    		   	    foreach($eis as $k=>$v){
	    		   	  	if($val == $v){
	    		   	  		unset($allnum[$key]);
	    		   	  	}
    		   	    }
    		    }
	   	    }

		    shuffle($allnum);
		    $get_number = array_slice($allnum,0,$order['num']);//抽取号码
            $code = json_encode($get_number);
		}
        return $code;
}


/*
 * 回收夺宝编码
 */
function indiana_recovery_code($id){
	
    $orderinfo = M('user_indiana')->where('id',$id)->find();
	$indianainfo = M('indiana_sale')->where("id",$orderinfo['indiana_id'])->find();
	if($indianainfo){
		$stock_num = $indianainfo['stock_num'] + $orderinfo['num'];//增加编号库存
        $r = M('indiana_sale')->where("id",$orderinfo['indiana_id'])->save(array('stock_num'=>$stock_num));	
        return $r;
	}
	else{
		$this->error('活动不存在或已被删除！',U('Admin/order/indiana_order_info/',array('id'=>$id)));
	}
		
	
}


/*
 * 生成二维码
 * $chl : 网址
 * $state : 参数(用户id)
 */
function getQRCode($chl,$state) 
{
    vendor("phpqrcode.phpqrcode");
    $dir = "./public/dist/qrcode/";
    if(!file_exists($dir)){
    	mkdir($dir);
    }
    $dir .= $state.".png";
    QRcode::png($chl,$dir);
    return "/public/dist/qrcode/".$state.".png";
} 


/*
 * 错误日志记录
 */
function log_error($msg){
	
	$log_dir = "./public/log/error_log.txt";
    file_put_contents($log_dir,$msg,FILE_APPEND);

}


/*
 * 一元夺宝开奖日志记录
 */
function log_indiana($msg){
	
	$log_dir = "./public/log/indiana_log.txt";
    file_put_contents($log_dir,$msg,FILE_APPEND);

}


/**
 * 发送站内消息
 * @author  soul
 * @param type 类型【1：全体   0：个人】  
 * @param category【0：物流消息  1：通知消息】
 * @param msg 消息内容
 * @param users array 接受消息的用户
 * @param $title 消息标题
 * @param $url 消息链接
 * @param $img 消息图片
 */
function SendMessage($type=1,$category=0,$msg,array $users=NULL,$title,$url='')
{

    $admin_id = empty(session('admin_id'))?0:session('admin_id');
    $message = array(
        'admin_id' => $admin_id,
        'message' => $msg,
        'category' => $category,
        'title' => $title,
        'url' => $url,
        'send_time' => time()
    );
    if ($type == 1) {
        //全体用户系统消息
        $message['type'] = 1;
        M('Message')->add($message);
    } else {
        //个体消息
        $message['type'] = 0;
        if (!empty($users)) {
            $create_message_id = M('Message')->add($message);            
            foreach ($users as $key) {
                M('user_message')->add(array('user_id' => $key, 'message_id' => $create_message_id, 'status' => 0, 'category' => $category));
            }
        }
    }
}

function getWx_access_token(){
    $wechat = M('wx_user')->find();
    $jssdk = new app\mobile\logic\Jssdk($wechat['appid'],$wechat['appsecret']);
    return  $jssdk->get_access_token();
}

/*
 * 发送微信模板消息
 */
function sendWXTemplateMessage($openid,$template_id,$data,$url=null){
    $access_token = getWx_access_token();
    $sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
    
    $post_data = array(
        'touser' => $openid,
        'template_id' => $template_id,
        'data' => $data,
        'url' => $url,
    );
    $json_data = json_encode($post_data);
    $result = json_decode(request_post($sendUrl,urldecode($json_data)),true);
    if($result['errcode'] == 0){
        return true;
    }else{
        return false;
    }
}

/**
 * 模拟post进行url请求
 * @param string $url
 * @param string $param
 */
function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 1);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);

    return $data;
}

/**
 * 模拟post进行url请求
 * @param string $url
 * @param string $param
 */
function api_notice_increment($url, $data){
    $ch = curl_init();
    $header = array("Accept-Charset: utf-8");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');

    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        curl_close( $ch );
        return $ch;
    }else{
        curl_close( $ch );
        return $tmpInfo;
    }
}

/**
 * 保存base64图片
 * @param array $imgarr
 * @param string $path
 * @param int $user_id
 */
function save_img_base64($imgarr,$path,$user_id) {
    if(is_array($imgarr)){
        $path = $path.Date("Y")."/";
        
        if(!is_dir($path)){//创建文件路径
            mkdir($path,0777);
        }
        $path = $path.Date("m-d")."/";
        if(!is_dir($path)){//创建文件路径
            mkdir($path,0777);
        }
        foreach ($imgarr as $key => $value){
            $imgsource = substr(strstr($value,','),1); //获取资源
            $data= base64_decode($imgsource); //转换base64编码
            $filename = md5(time().$user_id.$key).".png";
            $path1 = $path.$filename;
            //保留原始图片
            $result = file_put_contents($path1,$data);

            if($result <= 0){
                return 0; //文件保存失败
            }
            $img[] = substr($path1,1);
        }
        $imgarr = null;
        return $img; //操作成功
    }
    return -1; //资源格式错误
}


/**
 * 快递表即时查询
 */
function getOrderTracesByJson($OrderCode,$ShipperCode,$LogisticCode){
    $requestData= "{'OrderCode':'$OrderCode','ShipperCode':'$ShipperCode','LogisticCode':'$LogisticCode'}";

    $datas = array(
        'EBusinessID' => '1283607',
        'RequestType' => '8001',
        'RequestData' => urlencode($requestData) ,
        'DataType' => '2',
    );
    $ReqURL = "http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";
    $datas['DataSign'] = encrypt1($requestData, '7612f076-e72d-447b-8a7a-6e281a9f724a');
    $result=sendPost($ReqURL, $datas);

    //根据公司业务处理返回的信息......

    return $result;
}



/**
 * 快递鸟获取物流查询
 */
function get_shipping_info($ShipperCode,$LogisticCode,$CallBack) {
    $requestData="{'ShipperCode':'".$ShipperCode."','LogisticCode':'".$LogisticCode."','CallBack':'".$CallBack."'}";
    
    $datas = array(
        'EBusinessID' => '1283607',
        'RequestType' => '1008',
        'RequestData' => urlencode($requestData) ,
        'DataType' => '2',
    );
    $datas['DataSign'] = encrypt1($requestData, '7612f076-e72d-447b-8a7a-6e281a9f724a');
    //测试请求url
    $ReqURL = 'http://api.kdniao.cc/api/dist';
    //正式请求url
//     defined('ReqURL') or define('ReqURL', 'http://api.kdniao.cc/api/dist');
    $result=sendPost($ReqURL, $datas);
    return json_decode($result,true);;
}

/**
 *  post提交数据
 * @param  string $url 请求Url
 * @param  array $datas 提交的数据
 * @return url响应返回的html
 */
function sendPost($url, $datas) {
    $temps = array();
    foreach ($datas as $key => $value) {
        $temps[] = sprintf('%s=%s', $key, $value);
    }
    $post_data = implode('&', $temps);
    $url_info = parse_url($url);
    if(empty($url_info['port']))
    {
        $url_info['port']=80;
    }
    $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
    $httpheader.= "Host:" . $url_info['host'] . "\r\n";
    $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
    $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
    $httpheader.= "Connection:close\r\n\r\n";
    $httpheader.= $post_data;
    $fd = fsockopen($url_info['host'], $url_info['port']);
    fwrite($fd, $httpheader);
    $gets = "";
    $headerFlag = true;
    while (!feof($fd)) {
        if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
            break;
        }
    }
    while (!feof($fd)) {
        $gets.= fread($fd, 128);
    }
    fclose($fd);

    return $gets;
}


/**
 * 电商Sign签名生成
 * @param data 内容
 * @param appkey Appkey
 * @return DataSign签名
 */
function encrypt1($data, $appkey) {
    return urlencode(base64_encode(md5($data.$appkey)));
}

/**
 * 生成随机订单号
 */
function getOrdersn(){
    return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 生成缩略文件
 * @param $big_img 文件路径
 * @param $width 宽度
 * @param $height 高度
 * @return 缩略图路径
 */
function get_thume_img($big_img,$width,$height,$small_img){
    $imgage = getimagesize($big_img); //得到原始大图片
    switch ($imgage[2]) { // 图像类型判断
        case 1:
            $im = imagecreatefromgif($big_img);
            break;
        case 2:
            $im = imagecreatefromjpeg($big_img);
            break;
        case 3:
            $im = imagecreatefrompng($big_img);
            break;
    }
    $src_W = $imgage[0]; //获取大图片宽度
    $src_H = $imgage[1]; //获取大图片高度
    $tn = imagecreatetruecolor($width, $height); //创建缩略图
    imagecopyresampled($tn, $im, 0, 0, 0, 0, $width, $height, $src_W, $src_H); //复制图像并改变大小
    return imagejpeg($tn, $small_img); //输出图像
}


/*
 * 一元夺宝支付成功后获取编码  专为微信支付点对点异步调用
 */
function indiana_pay_ok($id){
 
    $order = M('user_indiana')->where('id',$id)->find();
    if($order['pay_status'] == 1){
    	exit('该订单已支付');
    }
    $indiana = M('indiana_sale')->where("id",$order['indiana_id'])->find();
    if($indiana['stock_num'] < $order['num']){
    	M('user_indiana')->where('id',$id)->save(array('order_status'=>7));//库存不足，订单过期
    	exit('您未及时付款，目前库存不足，订单已作废');
    	    }
 
    		//随机获取获奖号码
	if($indiana['indiana_number']){
	    $allnum = $ter = json_decode($indiana['indiana_number'],true);
	    $existNum = M('user_indiana')->where("indiana_id",$order['indiana_id'])->field("indiana_number")->select();
	    $eis = array();  		   
   	    foreach($existNum as $key=>$val){
   	    	if(!empty($val['indiana_number'])){
   	    	    $t = json_decode($val['indiana_number'],true);
   	  	        $eis = array_merge($eis,$t);	
   	    	}
   	    }
   	    if(!empty($eis)){
   	    	foreach($allnum as $key=>$val){
		   	    foreach($eis as $k=>$v){
    		   	  	if($val == $v){
    		   	  		unset($allnum[$key]);
    		   	  	}
		   	    }
		    }
   	    }

	    shuffle($allnum);
	    $get_number = array_slice($allnum,0,$order['num']);//抽取号码
	    $data['indiana_number'] = json_encode($get_number);
	}
	$r = M('user_indiana')->where('id',$id)->save($data);
	$a = indiana_order_action('pay',$id,'付款');
	if($r&$a){
		$stock_num = $indiana['stock_num'] - $order['num'];//减编号库存
	    M('indiana_sale')->where("id",$order['indiana_id'])->save(array('stock_num'=>$stock_num));
		exit('付款成功！');	
	}
	else{
		exit('获取开奖码失败，请联系管理员');
	}
}

//微信退款
function order_WX_refund($refund_id){
    //查询提款信息
    $refund_info = M('refund_log')->where('refund_id',$refund_id)->find();
    if($refund_info['status'] != 1){
        $data['out_trade_no'] = $refund_info['out_trade_no'];
        $data['out_refund_no'] = $refund_info['out_refund_no'];
        $data['total_fee']= (int)$refund_info['refund_fee'];
        $data['refund_fee']=    (int)$refund_info['refund_fee'];
        $data['op_user_id'] = "1400627102";//操作商户号
        // 导入具体的支付类文件
        include_once  "plugins/payment/weixin/weixin.class.php"; // D:\wamp\www\svn_tpshop\www\plugins\payment\alipay\alipayPayment.class.php
        $weixin = new Weixin();
        $result = $weixin->WX_refund($data);
        if($result['return_code'] == 'SUCCESS'){
            if($result['err_code']){
                M('refund_log')->where("refund_id",$refund_id)->save(array('err_msg'=>$result['err_code']));
                return false;
            }else{
                M('refund_log')->where("refund_id",$refund_id)->save(array('status'=>1));
                return true;
            }
        }else{
            M('refund_log')->where("refund_id",$refund_id)->save(array('err_msg'=>$result['return_msg']));
            return false;
        }
    }else{//已退款
        return true;
    }
}

//保存支付信息
function save_pay_info($recive_data){
    //数据截取
    $user_info = M("users")->where("openid",$recive_data['openid'])->find();
    $data['user_id'] = $user_info['user_id'];
    $data['transaction_id'] = $recive_data['transaction_id'];
    $data['out_trade_no'] =$recive_data['out_trade_no'];
    $data['order_sn'] =$recive_data['order_sn'];
    $data['total_fee'] =$recive_data['total_fee'];
    $data['bank_type'] =$recive_data['bank_type'];
    $data['trade_type'] =$recive_data['trade_type'];
    $data['openid'] =$recive_data['openid'];
    $data['pay_type'] = 'weixin';
    $data['time_end'] =$recive_data['time_end'];
    $result = M("pay_log")->where("order_sn",$data['order_sn'])->find();
    if(empty($result)){
       $result =  M("pay_log")->add($data);
    }
    return $result;
     
}

/*
 * 获取用户下线收益总额
 * param $user_id 用户id
 * param $income_per 分佣比例
 */
function get_distribut_income_detail($user_id,$income_per,$starttime=0,$endtime=0){
    //查询所有下线
    $map['first_leader'] = $user_id;
    if(!empty($starttime) && !empty($endtime)){
       $map['reg_time'] =['between',array($starttime,$endtime)];
    }
    $user_dis = M("users")->where($map)->select();

//     echo json_encode(M("users")->getLastSql());
//     exit;
    
    $distribut_order_count = 0;//总成交单数
    foreach ($user_dis as $key=>$value){
       //计算该下线收益总额
        $where['user_id'] = $value['user_id'];
        $where['pay_status'] = 1;
        $where['order_status'] = ['in',array(0,1,2,4)];
//         if(!empty($starttime) && !empty($endtime)){
//             $where['add_time'] = ['between',array($starttime,$endtime)];
//         }
        $distribut_order = M('order')->where($where)->order('order_id desc')->field("order_id,order_status,order_amount")->select();
        $user_dis[$key]['distribut_income'] = 0;
        $user_dis[$key]['distribut_income_count'] = 0;
        //查询收益列表
        foreach ($distribut_order as $ky=>$v){
            //查询订单详情中不参与分销的商品
            $order_goods_nodistribut = M("order_goods")
            ->alias("og")
            ->join("goods g","g.goods_id = og.goods_id")
            ->where("og.order_id = ".$v['order_id']." and g.is_distribut = 0")
            ->field("og.*,g.deduction_amount")
            ->select();
            $nodistribut_price = 0;//订单中不参与分销收益的商品总价
            if(!empty($order_goods)){
                foreach ($order_goods_nodistribut as $v1){
                    $nodistribut_price += ($v1['goods_price']-$v1['deduction_amount'])*$v1['goods_num'];
                }
            }
            if($v['order_status'] == 4){//已完成订单,算入收益记录
                $distribut_order_count++;
                //入账收收益
                $user_dis[$key]['distribut_income'] += ($v['goods_price'] - $nodistribut_price)*$income_per;
            }
            //获取总收益(预期收益)
            $user_dis[$key]['distribut_income_count'] += ($v['goods_price'] - $nodistribut_price)*$income_per;
        }
        $user_dis[$key]['distribut_income'] = sprintf("%.2f",$user_dis[$key]['distribut_income']);
        $user_dis[$key]['distribut_income_count'] = sprintf("%.2f",$user_dis[$key]['distribut_income_count']);
        $user_dis[$key]['reg_time'] = date("Y-m-d",$user_dis[$key]['reg_time']);
        $user_dis[$key]['user_id'] = sprintf("%09d",$user_dis[$key]['user_id']);
//         $distribut_incom += $user_dis[$key]['distribut_income'];//总收益
//         $distribut_income_count += $user_dis[$key]['distribut_income_count'];//总预期收益
    }

    return array(
        "distribut_income_detail"=>$user_dis,
//         "distribut_incom"=>$distribut_incom,
//         "distribut_income_count"=>$distribut_income_count,
        "distribut_order"=>$distribut_order_count,
        );
}



/*
 * 获取用户下线收益详情（收益流水）(按时间查询_待完善)
 * param $user_id 用户id
 * param $income_per 分佣比例
 */
function get_distribut_income_detail2($user_id,$income_per){
    //查询所有下线
    $user_dis = M("users")->where("first_leader",$user_id)->select();
    foreach ($user_dis as $key=>$value){
        $distribut_user[] =  $value['user_id'];
    }
    //获取所有有效订单
    $where['user_id'] = ['in',$distribut_user];
    $where['pay_status'] = 1;
    $where['order_status'] = ['in',array(0,1,2,4)];
    $distribut_order = M('order')->where($where)->order('order_id desc')->select();
    //查询收益列表
    foreach ($distribut_order as $key=>$value){
        //查询下线用户信息
        $dis_user_info = M('users')->where("user_id",$value['user_id'])->find();
        //查询订单详情中不参与分销的商品
        $order_goods_nodistribut = M("order_goods")
                        ->alias("og")
                        ->join("goods g","g.goods_id = og.goods_id")
                        ->where("og.order_id = ".$value['order_id']." and g.is_distribut = 0")
                        ->field("og.*")
                        ->select();
        $nodistribut_price = 0;//订单中不参与分销收益的商品总价
        if(!empty($order_goods)){
            foreach ($order_goods_nodistribut as $v){
                $nodistribut_price += $v['goods_price'];
            }
        }
        if($value['order_status'] == 4){//已完成订单,算入收益记录
            //本单收益
            $distribut_income = ($value['order_amount'] - $nodistribut_price)*$income_per;
            $distribut_income_list[] = array(
                'user_id'=> $dis_user_info['user_id'],
                'nickename'=> $dis_user_info['nickename'],
                'mobile'=> $dis_user_info['mobile'],
                'income'=> $distribut_income,
                'time' => $value['confirm_time'],//收货确认时间
            );
        }
        //获取总收益(预期收益)
        $distribut_income_count += ($value['order_amount'] - $nodistribut_price)*$income_per;
    }
    return array("distribut_income_list"=>$distribut_income_list,"distribut_income_count"=>$distribut_income_count);
}

//对二维数组排序
function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
    if(is_array($multi_array)){
        foreach ($multi_array as $row_array){
            if(is_array($row_array)){
                $key_array[] = $row_array[$sort_key];
            }else{
                return false;
            }
        }
    }else{
        return false;
    }
    array_multisort($key_array,$sort,$multi_array);
    return $multi_array;
}

//获取随机中奖率
function getRand($proArr) {
    $result = '';

    //概率数组的总概率精度
    $proSum = array_sum($proArr);

    //概率数组循环
    foreach ($proArr as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $proCur) {
            $result = $key;
            break;
        } else {
            $proSum -= $proCur;
        }
    }
    unset ($proArr);

    return $result;
}


//生成随机手机号码
function get_rand_mobile(){
    $arr = array(
        130,131,132,133,134,135,136,137,138,139,
        144,147,
        150,151,152,153,155,156,157,158,159,
        176,177,178,
        180,181,182,183,184,185,186,187,188,189,
    );
    return $arr[array_rand($arr)].mt_rand(1000,9999).mt_rand(1000,9999);
}



//计算用户星级
function user_stars($user_id){
	
	$count_num = M('users')->where(array('first_leader'=>$user_id,'mobile_validated'=>1))->count();
    if($count_num>=0 && $count_num<30){
    	return 0;
    }
    elseif($count_num >= 30 && $count_num<50){
    	return 1;
    }
    elseif($count_num>=50 && $count_num<100){
    	return 2;
    }
    elseif($count_num>=100 && $count_num<150){
    	return 3;
    }
    elseif($count_num >= 150 && $count_num<200){
    	return 4;
    }
    elseif($count_num >= 200 && $count_num<250){
    	return 5;
    }
    elseif($count_num >= 250 && $count_num<300){
    	return 6;
    }
    elseif($count_num >= 300){
    	return 7;
    }
}


//计算用户消费等级
function vip_level($user_id){
    $amount_sum = M('order')->where(array('user_id'=>$user_id,'pay_status'=>1))
                ->where('order_status in (0,1,2,4)')
                ->field('sum(goods_price) as goods_price,sum(discount) as discount')->find();
    //echo M('order')->getLastSql();
    if($amount_sum){
    	$total_amount = $amount_sum['goods_price']-$amount_sum['discount']; 
    	if($total_amount>0 && $total_amount<=3000){
    		return 0;
    	}
    	elseif($total_amount>3000 && $total_amount<=5000){
    		return 1;
    	} 
    	elseif($total_amount>5000 && $total_amount<=10000){
    		return 2;
    	}
    	elseif($total_amount>10000 && $total_amount<=15000){
    		return 3;
    	}
    	elseif($total_amount>15000 && $total_amount<=20000){
    		return 4; 
    	}
    	elseif($total_amount>20000 && $total_amount<=25000){
    		return 5;
    	}
    	elseif($total_amount>25000 && $total_amount<=30000){
    		return 6;
    	}
    	elseif($total_amount>30000){
    		return 7;
    	}
    }
}



/***
 * 兑换专区订单操作日志
 */
function exchange_order_action($action,$id,$msg){
	
    //状态说明
	//  pay 支付
	//  pay_cancel 取消支付
	//  delivery 发货
	//  stocking  备货
	//  delivery_cancel 取消发/备货
	//  receive 确认收货
	//  invalid 订单作废
	//  remove 移除
    
    $model = M('exchange_record');
    $user = session('user');
  
	$order_info = $model->where('id',$id)->find();
	if(!empty($order_info['order_action'])){
		$order_action = json_decode($order_info['order_action'],true);
	}
	else{
		$order_action = array();
	}
    
    if($action == 'insert'){    		
    	$push_action['status_desc'] = "提交兑换商品订单";
    }
    if($action == 'sure'){    		
    	$order_info['order_status'] = 1; //确认订单
    	$push_action['status_desc'] = "确认订单";
    } 
	if($action == 'delivery'){ //发货
		$order_info['shipping_status'] = 1; //设为已发货
    	$push_action['status_desc'] = "发货";
	}
	if($action == 'delivery_cancel'){ //取消发货
		$order_info['shipping_status'] = 0;
		$order_info['shipping_info'] = '';//清空物流数据;
    	$push_action['status_desc'] = "取消发货";
	}
	if($action == 'invalid'){ //取消订单
		$order_info['order_status'] = 3; //设为作废状态
    	$push_action['status_desc'] = "订单作废";
	}
	if($action == 'receive'){ //确认收货
		$order_info['order_status'] = 2; //确认收货
    	$push_action['status_desc'] = "确认收货，订单完成";
	}
	if($action == 'remove'){ //移除订单
		$a = M('user_indiana')->where(array('id'=>$recod_id))->delete();
		return $a;
	}

    $push_action['action_user'] = $user['user_id'];
    $push_action['order_status'] = $order_info['order_status'];
    $push_action['pay_status'] = $order_info['pay_status'];
	$push_action['action_note'] = $msg;
	$push_action['log_time'] = time();
    	
	array_push($order_action,$push_action);

	$order_info['order_action'] = json_encode($order_action);
	
	$msg = M('exchange_record')->where('id',$id)->save($order_info);
	return $msg;
}	
/**
 * 支付宝退货
 */
function alipay_refund(){
    // 导入具体的支付类文件
    include_once  "plugins/payment/alipayMobile/alipayMobile.class.php"; // D:\wamp\www\svn_tpshop\www\plugins\payment\alipay\alipayPayment.class.php
    $alipay = new alipayMobile();
    $result = $alipay->alipay_refund();
}

/**
 * 查询品酒站收益
*/
function get_station_income($station_id,$starttime = 0,$endtime = 0){
    //默认结束时间为当前时间
    $endtime = $endtime?$endtime:time();
    //查询站内成员
    $station_user = M("users")->where("station_id",$station_id)->select();
    //统计站内业绩
    $performance_count = 0;//总业绩
    foreach ($station_user as $k=>$v){
        //查询个人业绩(已完成+已收货订单，实际支付金额+余额抵扣)
        $user_order_pay_count = M('order')->where("user_id = ".$v['user_id']." and order_status in(2,4) and confirm_time>$starttime and confirm_time<$endtime")->sum('order_amount');
        $user_order_deduction_count = M('order')->where("user_id = ".$v['user_id']." and order_status in(2,4) and confirm_time>$starttime and confirm_time<$endtime")->sum('user_money');
        $performance_count += $user_order_pay_count;
        $performance_count += $user_order_deduction_count;
    }
    return $performance_count;
}
/**
 * 查询俱乐部成员业绩
 * @param unknown $user_id  用户id
 * @param number $starttime  开始时间
 * @param number $endtime   结束时间
 */
function get_station_member_income($user_id,$starttime = 0,$endtime = 0){
    //实际支付总额
    $user_order_pay_count = M('order')->where("user_id = ".$user_id." and order_status in(2,4) and confirm_time>$starttime and confirm_time<$endtime")->sum('order_amount');
    //余额支付总额
    $user_order_deduction_count = M('order')->where("user_id = ".$user_id." and order_status in(2,4) and confirm_time>$starttime and confirm_time<$endtime")->sum('user_money');
    
    return $user_order_pay_count + $user_order_deduction_count;
}


/**
 * 对二维数组进行排序
 * @param $array
 * @param $keyid 排序的键值
 * @param $order 排序方式 'asc':升序 'desc':降序
 * @param $type  键值类型 'number':数字 'string':字符串
 */
function sort_array(&$array, $keyid, $order = 'asc', $type = 'number') {
    if (is_array($array)) {
        foreach ($array as $val) {
            $order_arr[] = $val[$keyid];
        }
        $order = ($order == 'asc') ? SORT_ASC : SORT_DESC;
        $type = ($type == 'number') ? SORT_NUMERIC : SORT_STRING;
        array_multisort($order_arr, $order, $type, $array);
    }
}
